/**  
* @Title: CrWxUserController.java
* @Package com.lemon.controller.crwx
* @Description: (一句话阐述):
* @author Ran_cc
* @date 2018年11月8日
* @version V1.0  
*/
package com.lemon.controller.crwx;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.lemon.conf.MyException;
import com.lemon.model.cityRun.CrUserAddress;
import com.lemon.model.cityRun.CrUsersInfo;
import com.lemon.service.cityRun.CrUserService;
import com.lemon.utils.ReqResult;
import com.lemon.utils.TokenUtils;
import com.lemon.utils.sval.StaticValues;
import com.lemon.utils.wx.WxUtil;

/**
 * <p>Title: CrWxUserController</p>
 * <p>Description: 
 * </p>
 * <p>Company: </p>
 * @author Ran_cc
 * @date 2018年11月8日
 * @版本 V 1.0 
 */
@RestController
@RequestMapping("/xwx")
public class CrWxUserController {

	private static final Logger log = LoggerFactory.getLogger(CrWxUserController.class);

	@Resource
	private CrUserService uService;

	/**
	 * <b>Description:<blockquote>
	 * 查询wx用户信息
	 * </blockquote></b>
	 * 
	 * @Title: getWxUserInfo
	 * @param code
	 * @param iv
	 * @param encryptedData
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年8月9日
	 */
	@RequestMapping(value = "/getWxUserInfo" , method = RequestMethod.POST)
	public ReqResult getWxUserInfo(String code , String iv , String encryptedData , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			//			JSONObject wxOpenId = WxUtil.getWxOpenId(code);

			//			if (true) {
			//				return null;
			//			}
			JSONObject userInfo = WxUtil.getWxUserInfo(code , iv , encryptedData);
			log.info("code:{},iv:{},encryptedData:{}" , code , iv , encryptedData);
			String openid = userInfo.getString("openId");
			//判断openid是否存在
			CrUsersInfo byOpenId = uService.queryOauthInfoByOpenId(openid);
			CrUsersInfo tkUserInfo = null;
			//已存在 修改
			if (byOpenId != null) {
				CrUsersInfo tko = new CrUsersInfo();
				tko.setWxJsonInfo(userInfo.toJSONString());
				tko.setId(byOpenId.getId());
				if (!userInfo.getString("avatarUrl").equals(byOpenId.getHeadPic())
						|| !userInfo.getString("nickName").equals(byOpenId.getNickName())) {
					tko.setHeadPic(userInfo.getString("avatarUrl"));
					tko.setNickName(userInfo.getString("nickName"));
					uService.updateUserInfoById(tko);
					tkUserInfo = tko;
				} else {
					tkUserInfo = byOpenId;
				}
			} else {
				//不存在,添加
				CrUsersInfo tko = new CrUsersInfo();
				tko.setWxJsonInfo(userInfo.toJSONString());
				tko.setHeadPic(userInfo.getString("avatarUrl"));
				tko.setNickName(userInfo.getString("nickName"));
				tko.setWxOpenId(openid);
				tko.setStatus(1);
				tkUserInfo = uService.insertUserInfo(tko);
			}

			/*
			 * //保存登陆记录
			 * TkLoginRecord loginRecord = new TkLoginRecord();
			 * loginRecord.setLoginIp(IpUtils.getIpAddr(request));
			 * loginRecord.setLoginType(1);
			 * if (tkUserInfo != null) {
			 * loginRecord.setUserId(tkUserInfo.getId());
			 * loginRecord.setUserName(tkUserInfo.getUserName());
			 * loginRecord.setUserNickName(tkUserInfo.getNickName());
			 * loginRecord.setUserNo(tkUserInfo.getuId());
			 * loginRecord.setUserPhone(tkUserInfo.getPhoneNumber());
			 * } else {
			 * loginRecord.setUserNickName(userInfo.getString("nickName"));
			 * loginRecord.setUserName(openid);
			 * }
			 * try {
			 * loginRecord.setLoginState(1);
			 * userService.saveLoginRecord(loginRecord);
			 * } catch (Exception e) {
			 * MyException.writeErr(e , "保存登陆记录异常");
			 * }
			 */
			String tt = openid + "|" + StaticValues.APP_TYPE_WXXCX;
			String token = TokenUtils.createJwtToken(tt);
			response.setHeader("wxToken" , token);
			log.info("小程序登陆后返回的token:{}" , token);
			reqResult.setReturnResult(tkUserInfo);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "根据uid查询用户信息异常");
		}
		return reqResult;
	}

	///////////////////////////收货地址////////////////////////////////
	@RequestMapping("/getUserAddressList")
	public ReqResult getUserAddressList(@ModelAttribute CrUserAddress addr , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			addr.setOrderBy(" order by a.is_default desc , a.create_time desc ,a.id desc");
			List<CrUserAddress> list = uService.getUserAddressList(addr);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	@RequestMapping("/getUserInfoByUid")
	public ReqResult getUserInfoByUid(@ModelAttribute CrUsersInfo addr , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			addr.setOrderBy(" order by a.is_default desc , a.create_time desc ,a.id desc");
			List<CrUsersInfo> list = uService.selectListBySelective(addr);
			if (list.size() <= 0) {
				reqResult.setReturnResult("");
				return reqResult;
			}
			reqResult.setReturnResult(list.get(0));
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 新增用户收货地址
	 * </blockquote></b>
	 * 
	 * @Title: addUserAddressList
	 * @param addr
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月9日
	 */
	@RequestMapping(value = "/addUserAddress" , method = RequestMethod.POST)
	public ReqResult addUserAddress(@ModelAttribute CrUserAddress addr , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			addr.setStatus(1);
			int list = uService.addUserAddressList(addr);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 修改用户收货地址
	 * </blockquote></b>
	 * 
	 * @Title: addUserAddressList
	 * @param addr
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月9日
	 */
	@RequestMapping(value = "/updateUserAddres" , method = RequestMethod.POST)
	public ReqResult updateUserAddres(@ModelAttribute CrUserAddress addr , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			int list = uService.updateUserAddressList(addr);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "修改用户收货地址异常");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 修改用户收货地址
	 * </blockquote></b>
	 * 
	 * @Title: addUserAddressList
	 * @param addr
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月9日
	 */
	@RequestMapping(value = "/updateDefaultAddress" , method = RequestMethod.POST)
	public ReqResult updateDefaultAddress(@ModelAttribute CrUserAddress addr , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			int list = uService.updateDefauleAddress(addr);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "修改用户收货地址异常");
		}
		return reqResult;
	}

}
